package cn.wolfcode.trip.base.service.impl;


import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.mapper.TravelCommendMapper;
import cn.wolfcode.trip.base.mapper.TravelCommendMapper;
import cn.wolfcode.trip.base.query.TravelCommendQueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TravelCommendServiceImpl implements ITravelCommendService {

    @Autowired
    private TravelCommendMapper travelCommendMapper;


    @Override
    public PageInfo<TravelCommend> selectForList(TravelCommendQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),qo.getOrderBy());
        List<TravelCommend> list = travelCommendMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(TravelCommend travelCommend) {
        if (travelCommend.getId()==null) {
            //type==推荐攻略时，推荐攻略只需要一个
            if (travelCommend.getType()== TravelCommend.TYPE_STRATEGY) {
                travelCommendMapper.deleteByState();
            }

            travelCommendMapper.insert(travelCommend);
        }else {
            //当type!=推荐攻略,就需要在推荐攻略原有的基础之上加多一条
            Integer type=travelCommendMapper.selectTypeById(travelCommend.getId());
            if (type!= TravelCommend.TYPE_STRATEGY && travelCommend.getType()==TravelCommend.TYPE_STRATEGY) {
                travelCommendMapper.deleteByState();
            }

            travelCommendMapper.updateByPrimaryKey(travelCommend);
        }
    }

    @Override
    public List<Map<String, Object>> selectForType(TravelQueryObject qo) {
        Date date = new Date();

        //设置开始和结束的时间
        if (qo.getType()== TravelCommend.TYPE_WEEK) {
            Date sevenDaysAgo = DateUtil.getSevenDaysAgo(date);
            qo.setBeginDate(sevenDaysAgo);
        }else {
            Date aMonthAgo = DateUtil.getAMonthAgo(date);
            qo.setBeginDate(aMonthAgo);
        }
        Date endDate = DateUtil.getEndDate(date);
        qo.setEndDate(endDate);

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),qo.getOrderBy());
        List<Map<String, Object>> list = travelCommendMapper.selectForType(qo);
        return list;
    }



}
